import { useState, useEffect } from 'react';
import axios from '../utils/axios';
import { useParams, useNavigate } from 'react-router-dom';
import { AuthContext } from '../App';
import { useContext } from "react";
import { toast } from "sonner";
import Navbar from "@/components/Navbar";
// import { AuthContext } from '../App';

const notifications = [
    { id: 1, title: "新的患者申请", read: false },
    { id: 2, title: "保险审批通过", read: true },
    { id: 3, title: "系统维护通知", read: false }
];

interface RecordData {
    id: string;
    patientName: string;
    idNumber: string;
    date: string;
    medicalType: number;
    applyReason: string;
    prescription: string;
    applyAmount: number;
    status: number;
}

export default function Record() {
    const { logout } = useContext(AuthContext);
    const { id } = useParams();
    const [record, setRecord] = useState<RecordData | null>(null);
    const [loading, setLoading] = useState(true);
    const [showUserMenu, setShowUserMenu] = useState(false);
    const [showNotifications, setShowNotifications] = useState(false);
    const [userData, setUserData] = useState({
        name: "",
        avatar: "",
        role: ""
    });
    const navigate = useNavigate();

    const unreadCount = notifications.filter(n => !n.read).length;

    // 添加获取用户数据的函数
    const fetchUserData = async () => {
        try {
            const response = await axios.get('/api/v1/user', {
                withCredentials: true
            });
            setUserData(response.data);
        } catch (error) {
            console.error('获取用户数据失败:', error);
        }
    };

    const handleLogout = async () => {
        try {
            // 先调用后端退出接口
            await axios.post('/api/logout', {}, {
                withCredentials: true
            });

            // 然后执行前端退出逻辑
            logout();
            toast.success("已退出登录");
            navigate("/login");
        } catch (error) {
            console.error('退出登录失败:', error);
            toast.error('退出登录失败');
        }
    };

    const handleSignature = async (recordId: string, approved: boolean) => {
        try {
            const response = await axios.post(`/api/v1/medical-records/signature`, {
                recordId,
                approved
            });

            console.log("签名返回的结果: ", response.data);

            if (response.data.success && response.data.status === approved) {
                toast.success("操作成功");
                window.location.reload();
            } else {
                toast.error('操作失败，操作结果不一致');
            }
        } catch (error) {
            toast.error('内部错误');
        }
    };

    useEffect(() => {
        // console.log("id: ", id);
        const fetchRecord = async () => {
            try {
                const response = await axios.get(`/api/v1/medical-records/fetch/${id}`);
                console.log("record: ", response.data);
                setRecord(response.data.record);
            } catch (error) {
                console.error('获取记录失败:', error);
            } finally {
                setLoading(false);
            }
        };

        const checkAuth = async () => {
            try {
                const response = await axios.post('/api/check-auth', {}, {
                    withCredentials: true
                });
                if (!response.data.isAuthenticated) {
                    throw new Error('未登录');
                }
            } catch (error) {
                toast.error('请重新登录');
                logout();
                navigate('/login');
            }
        };

        checkAuth();
        fetchUserData(); // 新增调用
        fetchRecord();
    }, [id]);

    if (loading) {
        return <div className="p-6">加载中...</div>;
    }

    if (!record) {
        return <div className="p-6">未找到记录</div>;
    }

    return (
        <div className="min-h-screen bg-gray-100">
            {/* 顶部导航栏 */}
            <Navbar />

            {/* 内容区域 */}
            <main className="py-6 px-4 sm:px-6 lg:px-8">
                {/* 添加返回按钮 */}
                <div className="flex justify-between mb-4">
                    <button
                        onClick={() => navigate(-1)}
                        className="flex items-center text-gray-600 hover:text-gray-900"
                    >
                        <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 mr-1" viewBox="0 0 20 20" fill="currentColor">
                            <path fillRule="evenodd" d="M9.707 16.707a1 1 0 01-1.414 0l-6-6a1 1 0 010-1.414l6-6a1 1 0 011.414 1.414L5.414 9H17a1 1 0 110 2H5.414l4.293 4.293a1 1 0 010 1.414z" clipRule="evenodd" />
                        </svg>
                        返回
                    </button>

                    {/* 添加同意和拒绝按钮
                    <div className="flex mt-1 space-x-2">
                        <button
                            className="flex items-center rounded-md bg-green-500 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2"
                            onClick={() => handleSignature(record.id, true)}
                        >
                            <svg className="mr-2 h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7" />
                            </svg>
                            同意申请
                        </button>
                        <button
                            className="flex items-center rounded-md bg-red-500 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-red-600 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2"
                            onClick={() => handleSignature(record.id, false)}
                        >
                            <svg className="mr-2 h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
                            </svg>
                            拒绝申请
                        </button>
                    </div> */}
                </div>

                <div className="bg-white p-6 shadow-md rounded-lg">
                    <h1 className="text-2xl font-bold mb-6">医疗记录详情</h1>

                    <div className="space-y-4">
                        <div className="grid grid-cols-2 gap-4">
                            <div>
                                <h2 className="text-sm font-medium text-gray-500">患者姓名</h2>
                                <p className="mt-1 text-sm text-gray-900">{record.patientName}</p>
                            </div>
                            <div>
                                <h2 className="text-sm font-medium text-gray-500">身份证号</h2>
                                <p className="mt-1 text-sm text-gray-900">{record.idNumber}</p>
                            </div>
                        </div>

                        <div className="grid grid-cols-2 gap-4">
                            <div>
                                <h2 className="text-sm font-medium text-gray-500">就诊日期</h2>
                                <p className="mt-1 text-sm text-gray-900">{record.date}</p>
                            </div>
                            <div>
                                <h2 className="text-sm font-medium text-gray-500">就诊类型</h2>
                                <p className="mt-1 text-sm text-gray-900">
                                    {['门诊', '住院', '检查', '手术'][record.medicalType]}
                                </p>
                            </div>
                        </div>

                        {/* <div>
              <h2 className="text-sm font-medium text-gray-500">诊断结果</h2>
              <p className="mt-1 text-sm text-gray-900">{record.diagnosis}</p>
            </div> */}

                        <div>
                            <h2 className="text-sm font-medium text-gray-500">申请理由</h2>
                            <p className="mt-1 text-sm text-gray-900">{record.applyReason}</p>
                        </div>

                        {/* <div>
              <h2 className="text-sm font-medium text-gray-500">处方</h2>
              <p className="mt-1 text-sm text-gray-900">{record.prescription}</p>
            </div> */}

                        {/* <div>
              <h2 className="text-sm font-medium text-gray-500">费用</h2>
              <p className="mt-1 text-sm text-gray-900">¥{record.applyAmount.toFixed(2)}</p>
            </div> */}
                        <div className="grid grid-cols-2 gap-4">
                            <div>
                                <h2 className="text-sm font-medium text-gray-500">审批状态</h2>
                                {record.status === -1 ? (
                                    <div className="flex mt-1">
                                        <button
                                            className="mr-2 rounded-md bg-green-500 px-3 py-1 text-xs text-white hover:bg-green-600"
                                            onClick={() => handleSignature(record.id, true)}
                                        >
                                            同意
                                        </button>
                                        <button
                                            className="rounded-md bg-red-500 px-3 py-1 text-xs text-white hover:bg-red-600"
                                            onClick={() => handleSignature(record.id, false)}
                                        >
                                            拒绝
                                        </button>
                                    </div>
                                ) : (
                                    <p className="mt-1 text-sm text-gray-900">
                                        {['待处理', '已审批', '已拒绝'][record.status + 1]}
                                    </p>
                                )}
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    );
}
